<template>
  <div class="modify-container">
    <div class="form-card">
      <el-loading 
        :visible="loading || submitting"
        text="请稍候..."
        background="rgba(255, 255, 255, 0.8)">
      </el-loading>

      <div v-if="error" class="error-message">
        <el-alert
          :title="error"
          type="error"
          show-icon
          @close="error = ''">
        </el-alert>
      </div>

      <h2 class="form-title">
        <i class="el-icon-edit"></i>
        个人信息修改
      </h2>

      <!-- 当前信息显示区域 -->
      <div class="current-info">
        <h3>当前信息</h3>
        <div class="info-grid">
          <div class="info-item">
            <span class="label">用户名:</span>
            <span class="value">{{ currentInfo.uname }}</span>
          </div>
          <div class="info-item">
            <span class="label">联系方式:</span>
            <span class="value">{{ currentInfo.unum }}</span>
          </div>
          <div class="info-item">
            <span class="label">邮箱:</span>
            <span class="value">{{ currentInfo.uemail }}</span>
          </div>
          <div class="info-item">
            <span class="label">所属公司:</span>
            <span class="value">{{ currentInfo.ucompany }}</span>
          </div>
        </div>
      </div>
      
      <!-- 选择要修改的信息 -->
      <div class="modify-selection">
        <h3>选择要修改的信息</h3>
        <el-checkbox-group v-model="selectedFields">
          <el-checkbox label="uname">用户名</el-checkbox>
          <el-checkbox label="unum">联系方式</el-checkbox>
          <el-checkbox label="uemail">邮箱</el-checkbox>
          <el-checkbox label="ucompany">所属公司</el-checkbox>
          <el-checkbox label="upic">头像</el-checkbox>
        </el-checkbox-group>
      </div>

      <!-- 头像选择区域 - 仅在选择修改头像时显示 -->
      <div v-if="selectedFields.includes('upic')" class="avatar-section">
        <div class="current-avatar">
          <img :src="require(`@/assets/avatar/${form.upic || '1'}.png`)" alt="当前头像" />
          <div class="avatar-preview" v-if="form.upic !== currentInfo.uPic">
            <span>预览效果</span>
          </div>
        </div>
        <div class="avatar-options">
          <h4>选择新头像</h4>
          <div class="avatar-grid">
            <div 
              v-for="n in 10" 
              :key="n"
              class="avatar-option"
              :class="{ active: form.upic === String(n) }"
              @click="selectAvatar(n)"
            >
              <img :src="require(`@/assets/avatar/${n}.png`)" :alt="`头像${n}`" />
            </div>
          </div>
        </div>
      </div>

      <!-- 表单区域 - 仅显示选中要修改的字段 -->
      <el-form 
        ref="form" 
        :model="form" 
        :rules="rules"
        label-width="100px"
        class="info-form"
        v-if="!loading && selectedFields.length > 0"
      >
        <el-form-item 
          v-if="selectedFields.includes('uname')" 
          label="用户名" 
          prop="uname">
          <el-input v-model="form.uname" placeholder="请输入新的用户名"></el-input>
        </el-form-item>

        <el-form-item 
          v-if="selectedFields.includes('unum')" 
          label="联系方式" 
          prop="unum">
          <el-input v-model="form.unum" placeholder="请输入新的联系方式"></el-input>
        </el-form-item>

        <el-form-item 
          v-if="selectedFields.includes('uemail')" 
          label="邮箱" 
          prop="uemail">
          <el-input v-model="form.uemail" placeholder="请输入新的邮箱地址"></el-input>
        </el-form-item>

        <el-form-item 
          v-if="selectedFields.includes('ucompany')" 
          label="所属公司" 
          prop="ucompany">
          <el-input v-model="form.ucompany" placeholder="请输入新的公司名称"></el-input>
        </el-form-item>

        <el-form-item class="form-actions">
          <el-button 
            type="primary" 
            @click="submitForm" 
            :loading="submitting"
            :disabled="selectedFields.length === 0">
            保存修改
          </el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ModifyPersonal',
  data() {
    return {
      currentInfo: {}, // 存储当前信息
      selectedFields: [], // 选中要修改的字段
      form: {
        uname: '',
        unum: '',
        uemail: '',
        ucompany: '',
        upic: '1'
      },
      rules: {
        uname: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
          { pattern: /^[\u4e00-\u9fa5_a-zA-Z0-9]+$/, message: '只能包含中文、字母、数字和下划线', trigger: 'blur' }
        ],
        unum: [
          { required: true, message: '请输入联系方式', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
        ],
        uemail: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        ucompany: [
          { required: true, message: '请输入公司名称', trigger: 'blur' }
        ]
      },
      submitting: false,
      loading: false,
      error: '' // 添加错误信息存储
    }
  },
  created() {
    this.fetchUserInfo()
  },
  methods: {
    async fetchUserInfo() {
      this.loading = true;
      this.error = '';
      try {
        const response = await this.$http.get("/findUserById")
        if (response.data) {
          this.currentInfo = response.data
          // 修改字段映射以匹配后端返回的数据结构
          this.form = {
            uname: response.data.uRealName || '',    // 映射到 uRealName
            unum: response.data.uNum || '',          // 映射到 uNum
            uemail: response.data.uEmail || '',      // 映射到 uEmail
            ucompany: response.data.uCompany || '',  // 映射到 uCompany
            upic: response.data.uPic || '1'          // 映射到 uPic
          }
        }
      } catch (error) {
        this.error = '获取用户信息失败：' + (error.message || '未知错误');
        console.error('Error fetching user info:', error);
      } finally {
        this.loading = false;
      }
    },

    selectAvatar(n) {
      this.form.upic = String(n)
    },

    async submitForm() {
      try {
        await this.$refs.form.validate(async (valid) => {
          if (valid) {
            this.submitting = true;
            
            // 构建提交数据，使用后端需要的字段名
            const submitData = {
              // uID 会由后端根据当前登录用户获取，不需要前端传递
            };
            
            if (this.selectedFields.includes('uname')) {
              submitData.uRealName = this.form.uname;
            }
            if (this.selectedFields.includes('unum')) {
              submitData.uNum = this.form.unum;
            }
            if (this.selectedFields.includes('uemail')) {
              submitData.uEmail = this.form.uemail;
            }
            if (this.selectedFields.includes('ucompany')) {
              submitData.uCompany = this.form.ucompany;
            }
            if (this.selectedFields.includes('upic')) {
              submitData.uPic = this.form.upic;
            }

            // 打印提交的数据，用于调试
            console.log('Submitting data:', submitData);

            const response = await this.$http.post('/updateAccount', submitData);
            console.log('Server response:', response);
            
            // 修改判断条件，根据后端返回的实际数据结构判断
            if (response.data.code === 200 || response.data === true || response.status === 200) {
              this.$message({
                message: '修改成功',
                type: 'success',
                duration: 2000
              });
              await this.fetchUserInfo(); // 刷新信息
              this.selectedFields = []; // 清空选择
            } else {
              this.$message.error('修改失败：' + (response.data.message || '请稍后重试'));
            }
          } else {
            this.$message.error('请正确填写表单信息');
            return false;
          }
        });
      } catch (error) {
        console.error('提交表单时出错:', error);
        this.$message.error('提交出错：' + (error.message || '请重试'));
      } finally {
        this.submitting = false;
      }
    },

    resetForm() {
      this.$confirm('确定要重置表单吗？已填写的内容将会丢失', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$refs.form.resetFields();
        this.selectedFields = [];
        this.fetchUserInfo();
        this.$message({
          type: 'success',
          message: '已重置表单'
        });
      }).catch(() => {
        // 取消重置
      });
    }
  },
  beforeRouteLeave(to, from, next) {
    if (this.selectedFields.length > 0) {
      this.$confirm('有未保存的修改，确定要离开吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        next();
      }).catch(() => {
        next(false);
      });
    } else {
      next();
    }
  }
}
</script>

<style scoped>
.modify-container {
  padding: 24px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 48px);
}

.form-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 32px;
  max-width: 800px;
  margin: 0 auto;
}

.form-title {
  display: flex;
  align-items: center;
  margin: 0 0 32px;
  color: #303133;
  font-size: 24px;
}

.form-title i {
  margin-right: 8px;
  color: #409EFF;
}

.avatar-section {
  display: flex;
  gap: 32px;
  margin-bottom: 32px;
  padding: 24px;
  background: #f8f9fa;
  border-radius: 8px;
}

.current-avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: relative;
}

.current-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-options {
  flex: 1;
}

.avatar-options h4 {
  margin: 0 0 16px;
  color: #606266;
}

.avatar-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 16px;
}

.avatar-option {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.avatar-option:hover {
  transform: scale(1.05);
}

.avatar-option.active {
  border-color: #409EFF;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.avatar-option img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.info-form {
  max-width: 500px;
  margin: 0 auto;
}

.form-actions {
  margin-top: 32px;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .avatar-section {
    flex-direction: column;
    align-items: center;
  }

  .avatar-grid {
    grid-template-columns: repeat(5, 1fr);
  }

  .form-card {
    padding: 20px;
  }
}

/* 添加新样式 */
.current-info {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 24px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
  margin-top: 16px;
}

.info-item {
  display: flex;
  align-items: center;
}

.info-item .label {
  color: #606266;
  margin-right: 8px;
  min-width: 80px;
}

.info-item .value {
  color: #303133;
}

.modify-selection {
  margin-bottom: 24px;
}

.modify-selection h3 {
  margin-bottom: 16px;
}

:deep(.el-checkbox-group) {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

:deep(.el-checkbox) {
  margin-right: 0;
}

.error-message {
  margin-bottom: 20px;
}

::v-deep .el-loading-mask {
  z-index: 1000;
}

::v-deep .el-loading-text {
  font-size: 14px;
  margin-top: 10px;
}

.avatar-preview {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  padding: 4px;
  font-size: 12px;
  text-align: center;
}
</style>
